package com.guanyu.u2cache.redis;

import com.guanyu.u2cache.cache.CacheOperate;
import com.guanyu.u2cache.constant.RedisConstant;
import com.guanyu.u2cache.model.EventData;
import com.guanyu.u2cache.util.AddressUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;

import javax.annotation.Resource;

/**
 * @author zhouyunjian
 * @date 2023/11/14 14:29
 **/
@Slf4j
//@Component
public class RedisMsgListener implements ApplicationRunner, Ordered {
    @Autowired
    private RedissonClient redissonClient;
    @Resource
    private CacheOperate cacheOperate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("注册监听清空缓存时间开始");
        try {
            int retryCount = 10;
            int i=0;
            while (null==redissonClient&&i<retryCount){
                Thread.sleep(2000);
                i++;
            }
            RTopic topic = redissonClient.getTopic(RedisConstant.topic);
            topic.addListener(EventData.class, new MessageListener<EventData>() {
                @Override
                public void onMessage(CharSequence charSequence, EventData data) {
                    if (AddressUtil.getMacAddress().equals(data.getMacAddress())) {
                        log.debug("本机为源头机,无需重复处理,信息[{}]", data.toString());
                        return;
                    }
                    cacheOperate.clear(data.getCacheNames(), data.getKey(), data.getCacheType());
                }
            });
            log.info("注册监听清空缓存时间结束,redissonClent是否为空[{}]",null==redissonClient);
        }catch (Exception e){
            log.error("初始化启动出现异常,[{}]",e.getMessage(),e);
        }

    }

    @Override
    public int getOrder() {
        return 1;
    }
}
